<?php
/*
 * adapted from Multi plugin, original script by 12Christiaan.
 * modified by sowijo.
 */
class InvDelPlugin {
    var $ld;
    var $XMLconfig;
    var $xmlsOb;  //added by sowijo
    var $xmlsFName;  // added by sowijo
    // ==========================================================================
    function InvDelPlugin()
    {
        $this->ld = new LocalData();
        $this->xmlsOb = new xmlsOb();  //added by sowijo
        $xmlsFNameObj=new DelInvEnCfg();$this->xmlsFName=$xmlsFNameObj->langXML;
    }
    function flN($item){if(!isset($this->xmlsFName)||empty($this->xmlsFName)) return '-';if(isset($this->xmlsFName[$item])&&(!empty($this->xmlsFName[$item]))){return ((string)$this->xmlsFName[$item]);}else{return '';}}
    // ==========================================================================
    function GetForm($server)
    {
         echo '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" lang="ru">
 <head>
 <title>InvDel helper</title>
 <script src="..\..\codebase-php\jquery-1.4.2.min.js"></script>
 <script src="..\..\codebase-php\jquery.json-2.2.min.js"></script>
 <link href="helpers/menu.css" rel="stylesheet" type="text/css">
 <link href="helpers/plugin.css" rel="stylesheet" type="text/css">
 <script type="text/javascript" src="helpers/menu.js"></script>
<!--[if lte IE 7]>
<style>
#menuwrapper, #p7menubar ul a {height: 1%;}
a:active {width: auto;}
</style>
<![endif]-->
<script language="javascript">
<!--
function showimage() { if (!document.images) return
document.images.pictures.src=document.mygallery.picture.options[document.mygallery.picture.selectedIndex].value }
//-->
</script>
 <script>
 //======================================================================
  function changeText(){
                var boldtext = "<font style=\'font-weight:bold;font-size:13px;\'>"
      for(var key in window.nlist) {
          if(window.nlist[key]["uid"]==$("#nsp option:selected").attr("id")){
              var nbobj=window.nlist[key];
          }
      }
   
   if(nbobj!==undefined){
      var newDate = new Date();
      newDate.setTime(nbobj["lastplayed"]*1000);

      var sdiv="";
      sdiv="<br><br>"
      sdiv=sdiv+ "Name: &nbsp;&nbsp;" +boldtext+  nbobj["worldName"]+ "&nbsp( " + nbobj["uid"] + " )&nbsp </font><br>";

      $("#rcontent").html(sdiv);
                    }
  }
 //======================================================================
 $(document).ready(function(){';

echo '//===========================edit sowijo=========================
     window.activated=eval('.json_encode($this->ld->GetPlSettings('InvDelActivated')).');
     if ((window.activated!==null) && (window.activated!==undefined)) {
       var isrun=window.activated.cb_run_mainpage;
       if ((isrun!==true) && ((isrun!==false))) {
         isrun=false;
       } 
       $("#cb_run_mainpage").attr("checked", isrun); 
     }
     $("#cb_run_mainpage").change(function() {
       var req=new Object();
       var par=$(this).attr("id");
       var ischecked=$(this).attr("checked");
       req[par]=ischecked;
       ndata=$.toJSON(req); 
       var l=window.location.toString();
       var indx=l.indexOf(\'?\');
       var nurl=l.slice(0, indx)+"?action=activated&tmp="+Math.random();
       $.post(nurl, ndata);  //alert(ndata);
     });
     //===============edit sowijo, removing items===================== 
     $("#btn_RemoveGift").click(function(){
			var req1 = new Object();
			var req2 = new Object();
			var chkLength = $(":input").length;
			$(":input").each(function(i){
		       	if (i<chkLength/2)
		       		req1[$(this).attr("id")] = $(this).val();
		       	else
		       		req2[$(this).attr("id")] = $(this).val();
         });
			$(":checkbox").each(function(){  var par=$(this).attr("id");  req1[par]=$(this).attr("checked");   });
			data1=$.toJSON(req1);
			data2=$.toJSON(req2);
             var l=window.location.toString();
             var indx=l.indexOf(\'?\');
             var nurl=l.slice(0, indx)+"?action=RemoveGift&tmp="+Math.random();
			$.post(nurl, data1, function(r) { 
				$.post(nurl, data2, function(r) { 
					alert("Saved");
				});
			});
             return false;
     });
     $("input:[@type=text].InputRemove").change(function(){
       var item=$(this).attr("id").substr(5);
       var have=parseInt($("#RemHave_"+item).html());
       var keep=parseInt($(this).val(),10);
       if(isNaN(keep)==true){keep=9999;$(this).val(keep.toString());}
       if(keep<0){keep=9999;$(this).val(keep.toString());}
       if(have>keep){
         $("#RemMark_"+item).css("background-color","red");
       }
       else{
         $("#RemMark_"+item).css("background-color","transparent");
       }
     
       
     });
     $("input:[@type=text].InputRemove").keyup(function(){
       if($(this).val()!=""){
         $(this).trigger("change");
       }
     });
     //==============================================================
   }); // end document ready
  //======================================================================
  </script>
</head>
<body >
<table border="1" cellspacing="1" cellpadding="1" width="100%" bgcolor="#DDA0DD">
			  <tr height="23">
               <td><hr><h1>InvDel (by 12Christiaan) Version 0.2 (06 Jan 2011)</h1>
               <h5>(modified by sowijo, Images by BQ)</h5><hr></td>
              </tr>
			 </table>
			  <br>
			  <br>';
//*******************edit sowijo*******************
$b_active = (array)$this->ld->GetPlSettings('InvDelActivated'); $scb='';  
echo '<form>';
echo '<input type="checkbox" id="cb_run_mainpage" '.$scb.' />&nbsp;Run InvDel?&nbsp;'; 
echo '</form>';
//**********************************************
echo		'<div id="menuwrapper">
<ul id="p7menubar">
    <li><a href="/Plugins/InvDel/Main.php?action=menu&click=home">Home</a></li>
    <li><a class="trigger" href="#">General</a>
      <ul>
        <li><a href="/Plugins/InvDel/Main.php?action=menu&click=RemoveGift">Inventory DELETING Gifts</a></li>
      </ul>
    </li>
</ul>
<br class="clearit">
        <script language="javascript">
        P7_ExpMenu()
        </script>

</div>';
if($server['click'] == "home")
 {
    echo 'Welcome to the InvDel plugin for Cityville<br>';
    echo 'Made by 12christiaan<br>';
    echo '<span style="font-size:smaller;">modified by sowijo, Images by BQ</span><br>';
    echo '<br>';
    echo '<hr>';
 }
/***************edit sowijo, start of gift removing******************/
if($server['click'] == "RemoveGift")
 {
  $arRewards=array();
  foreach($this->xmlsOb->gsXML->randomModifierTables->randomModifierTable as $rmt){
    if(isset($rmt['type'])&&($rmt['type']=='mixed')){
      if(isset($rmt['name'])){
        $rmtname=(string)$rmt['name'];
        if(stripos($rmtname,'guestreward')!==false){
          if($rmtname[strlen($rmtname)-1]=='0'){
            foreach($rmt->roll as $roll){
              if(isset($roll->item)&&(isset($roll->item['name'])&&!empty($roll->item['name']))){
                $reward=(string)$roll->item['name'];
                $arRewards[$reward]=0;
              }
            }
          }
        }
      }
    }
  }

    $InvDelRemoveGift = (array)$this->ld->GetPlSettings('InvDelRemoveGift');
    $RemoveGiftKeep = array();
    foreach($InvDelRemoveGift as $Item => $Action)
    {
      if(substr($Item,0,5) == 'Remv_') { $ItemName = substr($Item, 5); $RemoveGiftKeep[$ItemName] = $Action; }
    }

        echo "<br>";
        echo '<div style="margin-left: 20px"><b>To DELETE Inventory gifts (after being deleted, it`s NOT recoverable!)</b>&nbsp;<hr><br>';
        echo '<form>';
        echo '<b>Step 1:</b>&nbsp;Select from each Items how many you like to KEEP (the rest will be DELETED).<br>';
        echo '<b>Step 2:</b>&nbsp;Press "Save settings" button in the bottom. <br>';

echo '<table class="table1">';
echo '<tr>
      <td>&nbsp</td>
      <td><b>Item Name</b></td>
	  <td><b>You have</b></td>
	  <td><b>Keep</b></td>
	  <td>Mark</td></tr>';
$sel = ($this->ld->GetSelect("SELECT count(*) as cnt FROM sqlite_master where tbl_name='Inventory'"));
$InvFileTot = array();

        $icons = array();
        $icons = $this->ld->Icons();

        $TotalGifts=0;
        if ($sel[0]["cnt"] == 1) {
          $sel = ($this->ld->GetSelect("SELECT count(*) as cnt FROM Inventory"));
          if ($sel[0]["cnt"] > 0) {
            $sel = ($this->ld->GetSelect("SELECT * FROM Inventory"));			
              foreach($sel as $k=>$n){
                $iname=(string)$n['Item'];
                if(isset($arRewards[$iname])){
                  $arRewards[$iname]=1;
                  $sel[$k]['rewardType']=0;
                }
                else{
                  $sel[$k]['rewardType']=9;
                }				
              }
              foreach($arRewards as $rk=>$rv){
                if($rv==0){
                  $sel[]=array('Item'=>$rk,'Number'=>0,'rewardType'=>0);
                }
              }
              usort($sel,'DelInv_Cmp');
              foreach ($sel as $n)
              {
                  $ItemName = (string)$n['Item'];
                  if($ItemName == "-"){continue;}
                  $ItemNumber = $n['Number'];
				  if ($ItemNumber == 0) {continue;}
                  $stitle=$this->flN($ItemName);$sback='';
                  if($n['rewardType']!=9){
                    $stitle.=' (rewards)';
                    $sback='style="background-color:#eee;"';
                  }
				  echo '<tr>
                        <td><img src="'.$icons[$ItemName].'" name="pictures" ></td>';			  
                  echo '<td>'.$ItemName.'</td><td '.$sback.' id="RemHave_'.$ItemName.'">'.$ItemNumber."</td>";
						
                  echo '<td '.$sback.'</td>';	
                  if(array_key_exists($ItemName, $RemoveGiftKeep))
                    { $value = $RemoveGiftKeep[$ItemName]; } else {$value = 95094187;}
                  echo '<input class="InputRemove" id="Remv_'.$ItemName.'" type="text" value="'.$value.'" size="4" '.$sback.' />';
                  $vItemNum = intval($ItemNumber);
                  $vItemKeep = intval($value);
                  $TotalGifts += $vItemNum;
                  if ($vItemNum>$vItemKeep) {$sstyle='style="background-color:red;"';} else {$sstyle='';}
                  echo '</td><td id="RemMark_'.$ItemName.'" '.$sstyle.'>&nbsp;</td></tr>';
              }
          }
        }

   echo'</table >There are '.$TotalGifts.' gifts in Inventory.<hr>';
   echo' <div width="100%" align="center"><br>
        <button id="btn_RemoveGift" style="color:white;background-color:#13a89e;border-width:1px;border-style:solid; ">&nbsp; Save settings&nbsp;</button>
       </div> </div>
    </form>';
   echo  "<b><br>Please, read the following remarks:<br>";
   echo  "&nbsp;-&nbsp;Be careful. There is no way to recover removed items.<br>";
   echo  "&nbsp;-&nbsp;When the gift is gone, it is gone.<br>";
   echo  "&nbsp;-&nbsp;Double check if you select the right items.<br>";
   echo  "&nbsp;-&nbsp;The amount of items in the list are only updated after a BOT cycle.<br></b>";
  unset($arRewards);
}
/***************edit sowijo, end of gift removing********************/
echo ' </body></html>';
}
}
function DelInv_Cmp($a,$b){
  $sa=(string)$a['rewardType'];$sb=(string)$b['rewardType'];$i=strcmp($sa,$sb);
  return ($i==0)?(strcmp($a['Item'],$b['Item'])):$i;
}
class DelInvEnCfg{var $langXML;function DelInvEnCfg(){$langdir=substr($_SERVER["PHP_SELF"],0,strpos($_SERVER["PHP_SELF"],"/")).'tmp_dir\en_US.xml';$langs=simplexml_load_file($langdir);$arFname=array();foreach($langs->pkg as $pkg){if($pkg['name']=='Items'){foreach($pkg->string as $fname){$fkey=substr((string)$fname['key'], 0, strpos((string)$fname['key'],'_friendlyName'));if(!empty($fkey)){$arFname[$fkey]=(string)$fname->original;}}}}$this->langXML=$arFname;}}
?>